# -*- coding: utf-8 -*-
"""
Market Data Service Configuration Module
Based on RedFire Framework Standard Configuration Format
"""
from typing import Optional, List, Dict, Any
from pydantic import BaseModel, Field
try:
    from pydantic_settings import BaseSettings
except ImportError:
    from pydantic import BaseSettings

# 导入RedFire框架配置基类
from backend.redfire_framework.core.config import (
    RedFireSettings, 
    MultiDatabaseServiceMixin
)


class TushareConfig(BaseSettings):
    """Tushare配置"""
    enabled: bool = Field(True, description="Enable Tushare adapter")
    token: str = Field("0f7f30453f483768fd15ecbac6d5a3198a688b36582e76b3f7ec81c5", description="Tushare API token")
    timeout: int = Field(30, description="API timeout in seconds")
    retry_count: int = Field(3, description="API retry count")
    retry_delay: float = Field(1.0, description="Retry delay in seconds")
    rate_limit_calls: int = Field(200, description="Rate limit: calls per period")
    rate_limit_period: int = Field(60, description="Rate limit period in seconds")
    
    model_config = {"env_prefix": "TUSHARE_", "env_file_encoding": "utf-8"}


class AKShareConfig(BaseSettings):
    """AKShare配置"""
    enabled: bool = Field(True, description="Enable AKShare adapter")
    timeout: int = Field(30, description="API timeout in seconds")
    retry_count: int = Field(3, description="API retry count")
    use_cache: bool = Field(True, description="Enable caching for AKShare requests")
    
    model_config = {"env_prefix": "AKSHARE_", "env_file_encoding": "utf-8"}


class CacheConfig(BaseSettings):
    """缓存配置"""
    default_ttl: int = Field(3600, description="Default cache TTL in seconds")
    max_size: int = Field(1000, description="Maximum cache size")
    cleanup_interval: int = Field(600, description="Cache cleanup interval")
    
    # L1 内存缓存配置
    l1_enabled: bool = Field(True, description="Enable L1 memory cache")
    l1_max_size: int = Field(100, description="L1 cache max size")
    l1_ttl: int = Field(300, description="L1 cache TTL")
    
    # L2 Redis缓存配置
    l2_enabled: bool = Field(True, description="Enable L2 Redis cache") 
    l2_ttl: int = Field(1800, description="L2 cache TTL")
    l2_prefix: str = Field("market_data:", description="L2 cache key prefix")
    
    # L3 数据库缓存配置
    l3_enabled: bool = Field(True, description="Enable L3 database cache")
    l3_ttl: int = Field(3600, description="L3 cache TTL")
    
    model_config = {"env_prefix": "CACHE_", "env_file_encoding": "utf-8"}


class RouterConfig(BaseSettings):
    """路由器配置"""
    enabled: bool = Field(True, description="Enable data source router")
    enable_auto_failover: bool = Field(True, description="Enable automatic failover")
    max_failover_attempts: int = Field(3, description="Maximum failover attempts")
    
    # 默认路由策略优先级列表
    default_priority: List[str] = Field(
        default=["tushare", "akshare", "influxdb"],
        description="Default adapter priority list"
    )
    
    # 能力匹配配置
    capability_min_score: float = Field(0.5, description="Minimum capability match score")
    capability_weight: float = Field(0.4, description="Capability matching weight")
    performance_weight: float = Field(0.25, description="Performance weight")
    freshness_weight: float = Field(0.2, description="Data freshness weight")
    reliability_weight: float = Field(0.1, description="Reliability weight")
    cost_weight: float = Field(0.05, description="Cost weight")
    
    model_config = {"env_prefix": "ROUTER_", "env_file_encoding": "utf-8"}


class ResilienceConfig(BaseSettings):
    """弹性层配置"""
    
    # 熔断器配置
    circuit_breaker_enabled: bool = Field(True, description="Enable circuit breaker")
    cb_failure_threshold: int = Field(5, description="Circuit breaker failure threshold")
    cb_success_threshold: int = Field(2, description="Circuit breaker success threshold")
    cb_timeout: float = Field(60.0, description="Circuit breaker timeout (seconds)")
    cb_half_open_max_calls: int = Field(3, description="Half-open state max calls")
    
    # 限流器配置
    rate_limiter_enabled: bool = Field(True, description="Enable rate limiter")
    rate_limit_requests: int = Field(100, description="Max requests per window")
    rate_limit_window: float = Field(60.0, description="Rate limit window (seconds)")
    
    # 重试配置
    retry_enabled: bool = Field(True, description="Enable retry mechanism")
    retry_max_attempts: int = Field(3, description="Maximum retry attempts")
    retry_base_delay: float = Field(1.0, description="Base delay for exponential backoff")
    retry_max_delay: float = Field(60.0, description="Maximum retry delay")
    
    # 超时配置
    default_timeout: float = Field(30.0, description="Default operation timeout")
    health_check_timeout: float = Field(5.0, description="Health check timeout")
    
    model_config = {"env_prefix": "RESILIENCE_", "env_file_encoding": "utf-8"}


class MonitoringConfig(BaseSettings):
    """监控配置"""
    enabled: bool = Field(True, description="Enable health monitoring")
    check_interval: float = Field(60.0, description="Health check interval (seconds)")
    unhealthy_threshold: int = Field(3, description="Consecutive failures to mark unhealthy")
    
    # 性能监控
    enable_metrics: bool = Field(True, description="Enable metrics collection")
    metrics_interval: float = Field(30.0, description="Metrics collection interval")
    
    model_config = {"env_prefix": "MONITORING_", "env_file_encoding": "utf-8"}


class DatabaseConfig(BaseSettings):
    """数据库配置 - 市场数据服务专用InfluxDB和Redis"""
    
    # Redis配置 - 缓存数据库
    redis_host: str = Field(default="localhost", description="Redis host")
    redis_port: int = Field(default=6379, description="Redis port")
    redis_password: str = Field(default="", description="Redis password")
    redis_db: int = Field(default=0, description="Redis database")
    
    # InfluxDB配置 - 时序数据库（主存储）
    influxdb_url: str = Field(default="http://localhost:8086", description="InfluxDB URL")
    influxdb_token: str = Field(default="", description="InfluxDB token")
    influxdb_org: str = Field(default="redfire_org", description="InfluxDB organization")
    influxdb_bucket: str = Field(default="redfire_bucket", description="InfluxDB bucket")
    
    model_config = {"env_file_encoding": "utf-8", "extra": "ignore", "case_sensitive": False}
    
    @property
    def redis_url(self) -> str:
        """构建Redis连接URL"""
        password_part = f":{self.redis_password}@" if self.redis_password else ""
        return f"redis://{password_part}{self.redis_host}:{self.redis_port}/{self.redis_db}"


class MarketDataServiceConfig(RedFireSettings, MultiDatabaseServiceMixin):
    """市场数据服务配置 - 继承RedFire框架配置"""
    
    # 覆盖基础服务配置
    service_name: str = Field(default="market-data-service", env="MARKET_DATA_SERVICE_NAME", description="Service name")
    service_version: str = Field(default="2.0.0", env="MARKET_DATA_SERVICE_VERSION", description="Service version")
    api_port: int = Field(default=8004, env="MARKET_DATA_API_PORT", description="Service port")
    
    # 数据源配置
    tushare: TushareConfig = Field(default_factory=TushareConfig)
    akshare: AKShareConfig = Field(default_factory=AKShareConfig)
    
    # 数据库配置
    database: DatabaseConfig = Field(default_factory=DatabaseConfig)
    
    # 缓存配置
    cache: CacheConfig = Field(default_factory=CacheConfig)
    
    # 路由器配置
    router: RouterConfig = Field(default_factory=RouterConfig)
    
    # 弹性层配置
    resilience: ResilienceConfig = Field(default_factory=ResilienceConfig)
    
    # 监控配置
    monitoring: MonitoringConfig = Field(default_factory=MonitoringConfig)
    
    # 数据获取配置
    batch_size: int = Field(default=1000, env="MARKET_DATA_BATCH_SIZE", description="Data batch size")
    max_concurrent_requests: int = Field(default=10, env="MARKET_DATA_MAX_CONCURRENT", description="Max concurrent requests")
    data_retention_days: int = Field(default=365, env="MARKET_DATA_RETENTION_DAYS", description="Data retention period in days")
    
    # 实时数据配置
    realtime_enabled: bool = Field(default=True, env="MARKET_DATA_REALTIME_ENABLED", description="Enable real-time data")
    websocket_heartbeat_interval: int = Field(default=30, env="MARKET_DATA_WS_HEARTBEAT", description="WebSocket heartbeat interval")
    
    # 性能配置
    enable_async_processing: bool = Field(default=True, env="MARKET_DATA_ASYNC_PROCESSING", description="Enable async processing")
    worker_pool_size: int = Field(default=4, env="MARKET_DATA_WORKER_POOL_SIZE", description="Worker pool size")
    
    # Adapter配置（新增）
    @property
    def ADAPTERS_CONFIG(self) -> Dict[str, Dict[str, Any]]:
        """
        适配器配置
        
        Returns:
            Dictionary mapping adapter names to their configurations
        """
        return {
            'tushare': {
                'enabled': True,
                'class': 'backend.services.market_data_service.app.adapters.providers.tushare.tushare_adapter.TushareAdapter',
                'config': {
                    'token': self.tushare.token,
                    'timeout': self.tushare.timeout,
                    'retry_count': self.tushare.retry_count,
                }
            },
            'akshare': {
                'enabled': True,  # 启用AkShare适配器，提供免费的分钟级K线数据
                'class': 'backend.services.market_data_service.app.adapters.providers.akshare.akshare_adapter.AkShareAdapter',
                'config': {
                    'timeout': self.akshare.timeout,
                    'retry_count': self.akshare.retry_count,
                    'use_cache': self.akshare.use_cache,
                }
            },
            'influxdb': {
                'enabled': True,
                'class': 'backend.services.market_data_service.app.adapters.providers.influxdb.influxdb_async_adapter.InfluxDBAsyncAdapter',
                'config': {
                    'url': self.database.influxdb_url,
                    'token': self.database.influxdb_token,
                    'org': self.database.influxdb_org,
                    'bucket': self.database.influxdb_bucket,
                }
            },
            # CTP adapter配置（默认禁用，需要手动配置）
            'ctp': {
                'enabled': False,
                'class': 'backend.services.market_data_service.app.adapters.providers.ctp.ctp_futures_adapter.CTPFuturesAdapter',
                'config': {
                    # 这些需要从环境变量或配置文件中加载
                    # 'broker_id': '...',
                    # 'user_id': '...',
                    # 'password': '...',
                    # 'md_address': '...',
                }
            },
            # RedFire Gateway adapter配置（默认禁用）
            'redfire_gateway': {
                'enabled': False,
                'class': 'backend.services.market_data_service.app.adapters.providers.redfire_gateway.redfire_gateway_adapter.RedFireGatewayAdapter',
                'config': {
                    # 'gateway_url': '...',
                    # 'api_key': '...',
                }
            },
        }
    
    def get_database_configs(self) -> Dict[str, Dict[str, Any]]:
        """实现多数据库配置 - 仅Redis缓存，InfluxDB使用单独适配器"""
        return {
            "cache": {
                "url": self.database.redis_url,
                "pool_size": 10,
                "timeout": 5,
                "type": "redis",
                "role": "cache"
            }
            # InfluxDB不通过DatabaseManager管理，使用单独的适配器
        }
    
    class Config:
        env_prefix = "MARKET_DATA_"
        env_file = ".env"
        env_file_encoding = "utf-8"
        case_sensitive = False


# 全局配置实例 - 使用框架标准方式
_config_instance: Optional[MarketDataServiceConfig] = None


def get_config() -> MarketDataServiceConfig:
    """获取配置实例 - 单例模式"""
    global _config_instance
    if _config_instance is None:
        _config_instance = MarketDataServiceConfig()
    return _config_instance


def reload_config() -> MarketDataServiceConfig:
    """重新加载配置"""
    global _config_instance
    _config_instance = MarketDataServiceConfig()
    return _config_instance


def get_tushare_config() -> TushareConfig:
    """获取Tushare配置"""
    return get_config().tushare


def get_cache_config() -> CacheConfig:
    """获取缓存配置"""
    return get_config().cache


def get_database_config() -> DatabaseConfig:
    """获取数据库配置"""
    return get_config().database


# 框架兼容函数
def get_market_data_settings(**overrides) -> MarketDataServiceConfig:
    """
    获取市场数据服务配置 - 框架标准接口
    
    Args:
        **overrides: 配置覆盖参数
        
    Returns:
        MarketDataServiceConfig: 配置实例
    """
    if overrides:
        # 如果有覆盖参数，创建新实例
        base_config = get_config()
        config_dict = base_config.dict()
        config_dict.update(overrides)
        return MarketDataServiceConfig(**config_dict)
    else:
        return get_config()


# 配置验证函数
def validate_config() -> bool:
    """验证配置完整性"""
    try:
        cfg = get_config()
        
        # 验证必要配置项
        if not cfg.service_name:
            raise ValueError("Service name is required")
        
        if cfg.port <= 0 or cfg.port > 65535:
            raise ValueError("Invalid port number")
        
        if cfg.batch_size <= 0:
            raise ValueError("Batch size must be positive")
        
        return True
        
    except Exception as e:
        print(f"Configuration validation failed: {e}")
        return False


if __name__ == "__main__":
    # 测试配置加载
    if validate_config():
        cfg = get_config()
        print(f"✅ Configuration loaded successfully: {cfg.service_name} v{cfg.service_version}")
        print(f"   Port: {cfg.port}")
        print(f"   Cache L1 enabled: {cfg.cache.l1_enabled}")
        print(f"   Tushare timeout: {cfg.tushare.timeout}s")
    else:
        print("❌ Configuration validation failed")